//
//  WaterInfoView.m
//  IphoneMapSdkDemo
//
//  Created by huck on 2017/5/22.
//  Copyright © 2017年 Baidu. All rights reserved.
//基本信息
//

#import "WaterInfoView.h"
#import "AppUtils.h"
#import "HomeManager.h"
#import "OutWaterView.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import "BMUtils.h"


@interface WaterInfoView()<BMKMapViewDelegate>

{
    
    BMKPointAnnotation* animatedAnnotation;
}

@property (nonatomic,strong) NSMutableArray *mapAnnotations; //标注的集合
@property (nonatomic,strong) NSMutableArray *mapAnnotationValues; //标注的集合
@property (nonatomic,strong) NSMutableArray *mapOverlays; //线的集合
@property (nonatomic,strong) WaterInfoDetailData *data;


@end

@implementation WaterInfoView

+ (instancetype)initViewWithFrameView:(UIView *)view
{
    if (nil == view) {
        return nil;
    }
    WaterInfoView *infoView = [[[NSBundle mainBundle] loadNibNamed:@"WaterInfoView" owner:nil options:nil] firstObject];
    [infoView setFrame:CGRectMake(0, 0, view.width, view.height)];
    [view addSubview:infoView];
    return infoView;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self initSubview];
}

-(void)initSubview{
    [HomeManager sharedInstance].waterDetailInfo = nil;
    _mapAnnotations = [NSMutableArray array];
    _mapOverlays = [NSMutableArray array];
    _mapAnnotationValues = [NSMutableArray array];
    _mapView.overlookEnabled = NO;
    _mapView.rotateEnabled = NO;

}

-(void)mapViewWillAppear
{
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}

-(void)mapViewWillDisappear
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
}

//整体刷新界面
-(void)updateInfo
{
    _data= [HomeManager sharedInstance].waterDetailInfo;
    
    _waterNameLabel.text = _data.waterName;
    _levelLabel.text = _data.waterQualityClassName;
    if([WATER_LEVEL5_BAD isEqualToString:_data.waterQualityClassName]){
        _levelLabel.textColor = [UIColor colorWithString:COLOR_FD6766];
    }else{
        _levelLabel.textColor = [UIColor colorWithString:COLOR_494B55];
    }
    _lengthLabel.text =_data.waterlength;
    if([AppUtils isNotEmpty:_data.waterlength]){
        _lengthLabel.text = [NSString stringWithFormat:@"%.1f",_data.waterlength.floatValue];
    }else{
        _lengthLabel.text = @"0";
    }
    _dutyLabel.text = _data.dutyName;
    
    [self updateBadReasonView];
    [self updateOutWaterView];
    [self updateMapInfo];
    
    _dutyAreaLabel.text = _data.dutyArea;
    _wLevelLabel.text = _data.waterLevelName;
    _lederLabel.text = _data.superviseName;
    
    
}

//刷新一点一策的界面
-(void)updateBadReasonView
{
//    if([AppUtils isNotEmptyArray:_data.badReasonAnalysis] && _data.showYDYC){
    if(_data.showYDYC){
        _badReasonView.hidden = NO;
        _badTitleH.constant = 40;
        _badReasonViewH.constant = 40 +5;
        
        [AppUtils clearSubView:_reasonContainner];
        CGFloat offy = 0;
        
        for(int i=0 ;i<_data.badReasonAnalysis.count;i++){
            BadReasonItemData *item = _data.badReasonAnalysis[i];
          UIView *addView  = [AppUtils addReasonView:CGRectMake(0, offy, _reasonContainner.width, 20) title:i==0?@"原因分析:":nil reasonLabel:[[HomeManager sharedInstance] getReanalysisLabel:item.value] resonDetail:item.detail showDetail:item.showDetail target:self selector:@selector(showDetailBtnClick:)];
            if(addView != nil){
                [_reasonContainner addSubview:addView];
                offy += addView.height;
                addView.tag = i;
            }
            
        }
        for(int i=0 ;i<_data.badManageScheme.count;i++){
            BadReasonItemData *item = _data.badManageScheme[i];
            UIView *addView  = [AppUtils addReasonView:CGRectMake(0, offy, _reasonContainner.width, 20) title:i==0?@"整改方案:":nil reasonLabel:[[HomeManager sharedInstance] getMaschemeLabel:item.value] resonDetail:item.detail showDetail:item.showDetail target:self selector:@selector(showDetailBtnClick:)];
            if(addView != nil){
                [_reasonContainner addSubview:addView];
                offy += addView.height;
                addView.tag = i+100;
            }
        }
        _badReasonViewH.constant +=offy;
    }else{
        _badReasonView.hidden = YES;
        _badReasonViewH.constant = 0;
        _badTitleH.constant = 0;
    }
}

//刷新排污口界面
-(void)updateOutWaterView
{
    if([AppUtils isNotEmptyArray:_data.positionList]){
        _outWaterView.hidden = NO;
        _outTitleH.constant = 40;
        _outWaterViewH.constant = 40 + 15;
        
        [AppUtils clearSubView:_outWaterContainer];
        CGFloat offy = 0;
        for (int i=0;i<_data.positionList.count;i++){
            PositionInfoData *item = _data.positionList[i];
            if([@"00" isEqualToString:item.status]){
                continue;
            }
            UIView *vv = [[UIView alloc] initWithFrame:CGRectMake(0, offy, _outWaterContainer.width, 100)];
            [_outWaterContainer addSubview:vv];
            offy+=100;
            OutWaterView *outW = [OutWaterView initViewWithFrameView:vv];
            [outW setContent:item];
        }
        _outWaterViewH.constant += offy;
        if(offy==0){
            _outWaterView.hidden = YES;
            _outTitleH.constant = 0;
            _outWaterViewH.constant = 0;
        }
    }else{
        _outWaterView.hidden = YES;
        _outTitleH.constant = 0;
        _outWaterViewH.constant = 0;
    }
}

-(void)showDetailBtnClick:(UIGestureRecognizer *) recognizer
{
    NSInteger tag = [recognizer.view superview].tag;
    if(tag>=100 && tag-100<_data.badManageScheme.count){
        BadReasonItemData *item = _data.badManageScheme[tag-100];
        item.showDetail = !item.showDetail;
        
    }else if(tag>=0 && tag<_data.badReasonAnalysis.count){
        BadReasonItemData *item = _data.badReasonAnalysis[tag];
        item.showDetail = !item.showDetail;
    }
    [self updateBadReasonView];
}

//显示地图
-(void)updateMapInfo
{
    //设置坐标中心点
    if([BMUtils canMakePoint:_data.mapTag]){
        [_mapView setCenterCoordinate:[BMUtils getPoint:_data.mapTag] animated:NO];
        _mapView.zoomLevel = _data.mapLevel;
    }

    [_mapView removeAnnotations:_mapAnnotations];
    [_mapAnnotations removeAllObjects];
    [_mapAnnotationValues removeAllObjects];
    [_mapView removeOverlays:_mapOverlays];
    [_mapOverlays removeAllObjects];
    
    if([AppUtils isNotEmptyArray:_data.positionList]){
        for(PositionInfoData *item in _data.positionList){
            if([AppUtils isNotEmpty:item.position]){
                if([@"00" isEqualToString:item.status]){ //折线水体范围
                    NSArray *pointsArr = [item.position componentsSeparatedByString:@";"];
                    NSMutableArray *points = [NSMutableArray arrayWithArray:[pointsArr copy]];
                    [points addObject:pointsArr.firstObject];
                    NSMutableArray *colorIndexs = [NSMutableArray array];
                    int j = 0;
                    
                    CLLocationCoordinate2D *coors;
                    coors = (CLLocationCoordinate2D *)malloc(points.count*sizeof(CLLocationCoordinate2D));//为结构体分配存储空间
                    for(int i=0;i<points.count;i++){
                        NSString *pointStr = points[i];
                        if([BMUtils canMakePoint:pointStr]){
                            coors[i] = [BMUtils getPoint:pointStr];
                            j++;
                            //构建分段颜色索引数组
                            [colorIndexs addObject:[NSNumber numberWithInt:0]];
                        }
                    }
                    //构建BMKPolyline,使用分段颜色索引，其对应的BMKPolylineView必须设置colors属性
                    BMKPolyline *colorfulPolyline = [BMKPolyline polylineWithCoordinates:coors count:j textureIndex:colorIndexs];
                    [_mapOverlays addObject:colorfulPolyline];
                    [_mapView addOverlays:_mapOverlays];
                    
                }else{ //标注排污口
                    if([BMUtils canMakePoint:item.position]){
                        BMKPointAnnotation * pointAnnotation = [[BMKPointAnnotation alloc] init];
                        pointAnnotation.coordinate = [BMUtils getPoint:item.position];
                        pointAnnotation.title = item.dirtyName;
                        [_mapAnnotations addObject:pointAnnotation];
                        [_mapAnnotationValues addObject:[AppUtils toStr:item.isDirect]];
                    }
                }
            }
        }
        [_mapView addAnnotations:_mapAnnotations];
    }
}


#pragma mark ==========================地图相关==========================

- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay
{
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.lineWidth = 2;
        /// 使用分段颜色绘制时，必须设置（内容必须为UIColor）
        polylineView.colors = @[[AppUtils getQualityClass:_data.waterQualityClassName]];
        return polylineView;
    }
    return nil;
}

// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //普通annotation
    NSInteger index = [_mapAnnotations indexOfObject:annotation];
    if(index>=0 && index<_mapAnnotations.count){
        BOOL isDirect = [AppUtils toString:_mapAnnotationValues[index]].boolValue;
        NSString *AnnotationViewID = @"AnimatedAnnotation";
        BMKAnnotationView *annotationView = (BMKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            [annotationView setBounds:CGRectMake(0.f, 0.f, 20.f, 20.f)];
            [annotationView setBackgroundColor:[UIColor clearColor]];
            UIImageView *icon = [[UIImageView alloc] initWithFrame:annotationView.bounds];
            icon.tag = 100;
            [annotationView addSubview:icon];
            icon.contentMode = UIViewContentModeScaleToFill;
        }
        UIImageView *icon = [annotationView viewWithTag:100];
        icon.image = [UIImage imageNamed: isDirect ? @"bad_water_river_yes":@"bad_water_river_no"];
        return annotationView;
    }
    return nil;
}

- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

@end
